<?php

namespace App\Admin\Controllers;

use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\ProductSku;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Collection;
use function AlibabaCloud\Client\json;

class ProductController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Product());
        $grid->filter(function ($filter) {
            $filter->column(1/2,function ($filter) {
                $filter->like('title','商品的名称');
            });

        });
        $grid->column('id', 'Id');
        $grid->column('category_id', '所属分类')->display(function ($id) {
            if ($category=ProductCategory::find($id)) {
                return $category->name;
            }else {
                return '暂无分类';
            }
        });
//        $grid->column('store_id', __('Store id'));
        $grid->column('title', '商品名称');
        $grid->column('introduce', '简介');
//        $grid->column('description', __('Description'));
        $grid->column('image', '展示图片')->image('',100);
        $grid->column('on_sale', '是否售卖');
        $grid->column('sold_count', '销量');
        $grid->column('review_count', '评论数');
        $grid->column('price', '价格');
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Product::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('category_id', __('Category id'));
        $show->field('store_id', __('Store id'));
        $show->field('title', __('Title'));
        $show->field('introduce', __('Introduce'));
        $show->field('description', __('Description'));
        $show->field('image', __('Image'));
        $show->field('on_sale', __('On sale'));
        $show->field('sold_count', __('Sold count'));
        $show->field('review_count', __('Review count'));
        $show->field('price', __('Price'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }


    protected function form()
    {
        $form = new Form(new Product());
        $form->select('category_id', '所属分类')->options(ProductCategory::selectOptions())->required();
//        $form->number('store_id', __('Store id'));
        $form->text('title', '商品的标题')->required();
        $form->text('introduce', '商品的简介')->required();
        $form->image('image', '展示图片')->removable()->required();
        $form->editor('description', '商品的内容')->required();
        $form->switch('on_sale', '是否售卖')->default(1);
        if ($form->isEditing()) {
            $product=Product::find(request()->route('product'));
            if ($product->skus->isNotEmpty()) {
                //变量不为空初始化变量sku渲染数据
                $skusData=$this->applySkuData($product->skus);
                $form->sku('sku', '商品的规格')->default($skusData);
//                dd($skusData);
            }
        }else {
            $form->sku('sku', '商品的规格');
        }

        $form->ignore(['sku']);
        //计算最低的价格
        $form->saving(function (Form $form) {
            $skus = json_decode(request('sku'), true);
            if ($skus['type'] == 'many') {
                $price = collect($skus['sku'])->pluck('price')->min() ?: 0;
                $form->model()->price = $price;
            } else {
                $form->model()->price = 0;
            }
            $form->model()->store_id=1;
        });

        //将sku 保存到sku列表
        $form->saved(function (Form $form) {
            $skus=[];
            $requestSku=json_decode(request('sku'),true);
            //判断是创建还是更新
            if (request()->isMethod('PUT')) {
                //todo 删除所有数据并重新创建
                $form->model()->skus()->delete();
            }
            foreach ($requestSku['sku'] as $item) {
                $skus[] =[
                    'attrs' => json_encode($requestSku['attrs'],JSON_UNESCAPED_SLASHES),
                    'sku' => collect($item)->intersectByKeys(['price','item'])->toJson(),
                    'price' => $item['price'],
                    'stock' =>$item['stock'],
                ];
            }
            $form->model()->skus()->createMany($skus);
        });
        return $form;
    }

    /**
     * 将sku 数据转换为能渲染道组件中的数据
     * @param Collection $sku
     * @return false|string
     */
    public function applySkuData($sku)
    {
        $data=[
            'type'=>'many',
            'attrs'=>json_decode($sku->first()->attrs,true)
        ];
       //将sku信息批量添加
        $sku->each(function ($item) use(&$data){
            $itemData=json_decode($item->sku,true);
            $itemData['price']=$item->price;
            $itemData['stock']=$item->stock;
            $itemData['id']=$item->id;
            $data['sku'][]=$itemData;
        });
        return json_encode($data,JSON_UNESCAPED_SLASHES);
    }
}
